package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.security.MessageDigest;
import java.util.Scanner;

import model.User;

public class LoginClient {
	private Socket client;
	private DataInputStream fromServer;
	private DataOutputStream toServer;
	private ObjectInputStream objFromServer;
	
	private Scanner sc;
	
	public LoginClient(String host, int port){
		try {
			sc = new Scanner(System.in);
			client = new Socket(host, port);
			fromServer = new DataInputStream(client.getInputStream());
			toServer = new DataOutputStream(client.getOutputStream());
			objFromServer = new ObjectInputStream(client.getInputStream());
			
			System.out.println(fromServer.readUTF());
//			process();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void process(){
		boolean connected = true;
		while(connected){
			sendMessage("LOGIN");
			System.out.print("username: ");
			sendMessage(sc.nextLine());
			System.out.print("password: ");
			sendMessage(md5(sc.nextLine()));
			
			User user = receiveUser();
			if(user != null){
				System.out.println(user);
			}else{
				System.out.println("Your username or password is invalid");
			}
		}
	}
	
	public User getUser(String username, String password){
		sendMessage("LOGIN");
		sendMessage(username);
		sendMessage(md5(password));
		return receiveUser();
	}
	
	public void sendMessage(String message){
		try {
			toServer.writeUTF(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public User receiveUser(){
		try {
			return (User)objFromServer.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String md5(String text) {
		String checksum = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] buffer = text.getBytes();
			md.update(buffer);
			byte[] hash = md.digest();
			checksum = String.format("%032x", new BigInteger(1, hash));
		} catch (Exception ex) {
			System.out.println(ex);
		}

		return checksum;
	}
	
	public static void main(String[] args) {
		new LoginClient("localhost", 7764);
	}
	
	
}
